document.addEventListener('DOMContentLoaded', function() {  
    var usernameInput = document.getElementById('username');  
    var passwordInput = document.getElementById('password');  
  
    // 为两个输入框添加键盘事件监听器  
    usernameInput.addEventListener('keydown', function(event) {  
        if (event.key === 'Enter') {  
            if (passwordInput.value.length > 1){
                login();
            }else{
                console.log("等待输入密码");
            }
        }  
    });  
  
    passwordInput.addEventListener('keydown', function(event) {  
        if (event.key === 'Enter') {  
            if (passwordInput.value.length > 1){
                login();
            }else{
                console.log("等待输入密码");
            }
        }  
    });  
});

function login(url_value) {
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    var url = `http://${url_value}:10801/login`;
    console.log(`请求【${url}】`)
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username: username, password: password })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        // { success: true } 表示登录成功
        if (data.status === 0) {
            // document.getElementById('msg').textContent = '登录成功！';
            // 这里可以重定向到另一个页面，例如：
            window.location.href = `background/workbench?sid=${data.sid}&username=${data.user_name}`;
        } else {
            alert(data.msg)
        }
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
        document.getElementById('message').textContent = '登录失败，请检查网络连接。';
        alert('登录失败，请检查网络连接。')
    });
};